<?php
// 应用公共文件

//表定义
use app\tools\Workerman;
use think\helper\Str;

const WebsiteTable = 'website';   //网站设置表
const AdminTable = 'admin';   //管理员
const AdminRoleTable = 'admin_role';   //管理员角色
const AdminLoginTable = 'admin_login';   //管理员登录
const AdminWxLogTable = 'admin_wx_log';   //管理微信记录
const MenuTable = 'menu';   //菜单表
const RoleTable = 'role';   //菜单表
const UserTable = 'user';   //用户表
const UserWxTable = 'user_wx';   //用户微信表

//商城
const GoodsClassifyTable = 'goods_classify';   //商品分类
const GoodsInfoTable = 'goods_info';   //商品信息
const GoodsSpecTable = 'goods_spec';   //商品规格
//内容
const ArticleTable = 'article';  //文章表
const ArticleClassifyTable = 'article_classify';  //文章分类表
//视频
const VideoClassifyTable = 'video_classify';  //视频分类表
const VideoInfoTable = 'video_info';  //视频信息表
const VideoSeriesTable = 'video_series';  //视频剧集表
//音乐
const MusicTable = 'music';  //音乐信息


const ChatAddLogTable = 'chat_add_log';  //聊天室记录表
const ChatSpeakLogTable = 'chat_speak_log';  //聊天室记录表


//微信相关表
const WxQrTable = 'wx_qr';  //微信二维码表

/*---------自定义函数----------*/

if (!function_exists('getCode')) {
    /**
     * 随机验证码
     *
     * User : Du
     * Date : 2021/12/8
     * Time : 10:24
     * @param int $len 长度 默认：6
     * @param int $type 1：大写+小写+数字 2：大写+小写3：大写字母 4：小写字母 5：0-9 6：1-9 默认：小写字母+数字
     * @return string
     */
    function getCode(int $len = 6, int $type = 0): string
    {
        $code = '';
        switch ($type) {
            case 1:
                $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                break;
            case 2:
                $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                break;
            case 3:
                $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
            case 4:
                $string = 'abcdefghijklmnopqrstuvwxyz';
                break;
            case 5:
                $string = '0123456789';
                break;
            case 6:
                $string = '123456789';
                break;
            default:
                $string = 'abcdefghijklmnopqrstuvwxyz0123456789';
        }
        $arr = str_split($string);
        for ($i = 0; $i < $len; $i++) {
            $code .= $arr[array_rand($arr)];
        }
        return $code;
    }
}

if (!function_exists('getIp')) {
    /**
     * 获取用户端ip
     *
     * User : Du
     * Date : 2021/12/8
     * Time : 10:30
     * @return string
     */
    function getIp(): string
    {
        $realIp = '';
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $realIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realIp = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                $realIp = $_SERVER['REMOTE_ADDR'];
            }
        } else if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realIp = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('HTTP_CLIENT_IP')) {
            $realIp = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('REMOTE_ADDR')) {
            $realIp = getenv('REMOTE_ADDR');
        }
        return $realIp;
    }
}

if (!function_exists('isHTTPS')) {
    /**
     * 服务器是否支持https
     *
     * User : Du
     * Date : 2021/12/8
     * Time : 10:31
     * @return string
     */
    function isHTTPS(): string
    {
        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            return 'https://';
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            return 'https://';
        } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            return 'https://';
        }
        return 'http://';
    }
}

if (!function_exists('getVersionNumber')) {
    /**
     * 文件加版本信息
     *
     * User : Du
     * Date : 2021/12/8
     * Time : 10:32
     * @param string $path
     * @return string
     */
    function getVersionNumber(string $path): string
    {
        if (!is_file(public_path() . $path)) {
            return $path;
        }
        $time = filemtime(public_path() . $path);
        return $path . '?v=' . $time;
    }
}

if (!function_exists('curl')) {
    /**
     * curl 请求
     *
     * User : Du
     * Date : 2021/12/8
     * Time : 10:38
     * @param string $url
     * @param array $postData
     * @return false|mixed
     */
    function curl(string $url = '', array $postData = [])
    {
        if (!$url) {
            return false;
        }
        $header = array(
            "Content-type:application/x-www-form-urlencoded;charset=UTF-8"
        );
//        $header = array("Content-type:application/json;", "Accept:application/json");
        $curl = curl_init();  //初始化
        curl_setopt($curl, CURLOPT_URL, $url);  //设置抓取的url
        curl_setopt($curl, CURLOPT_HEADER, 0);  //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);      // 超时设置
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);  // 超时设置，以毫秒为单位
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);  // 设置请求头
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($postData) {
            $postData = arrayToJson($postData);
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        }
        //执行命令
        $data = curl_exec($curl);
        curl_close($curl);
        return jsonToArray($data);
    }
}

if (!function_exists('toCamelCase')) {
    /**
     * 下划线转驼峰
     *
     * User : Du
     * Date : 2021/12/8
     * Time : 10:44
     * @param array $arr
     * @return array
     */
    function toCamelCase(array $arr = []): array
    {
        if (!$arr) {
            return [];
        }
        $newArr = [];
        foreach ($arr as $k => $v) {
            $key = Str::camel($k);
            if (is_array($v)) {
                $newArr[$key] = toCamelCase($v);
            } else {
                if (in_array($key, ['createTime', 'updateTime', 'deleteTime'])) {
                    $v = date('Y-m-d H:i:s', $v);
                }
                $newArr[$key] = $v;
            }
        }
        return $newArr;
    }
}

if (!function_exists('toUnderScore')) {
    /**
     * 驼峰转下划线
     *
     * User : Du
     * Date : 2021/8/16
     * Time : 12:00
     * @param array $arr
     * @return array
     */
    function toUnderScore(array $arr = []): array
    {
        if (!$arr) {
            return [];
        }
        $newArr = [];
        foreach ($arr as $k => $v) {
            $key = Str::snake($k, '_');
            if (is_array($v)) {
                $newArr[$key] = toUnderScore($v);
            } else {
                $newArr[$key] = $v;
            }
        }
        return $newArr;
    }
}

if (!function_exists('getYearHolidays')) {
    /**
     * 获取当前年份节假日和调休
     *
     * User : Du
     * Date : 2021/10/14
     * Time : 10:47
     * @return array|false
     */
    function getYearHolidays()
    {
        $redis = new \think\cache\driver\Redis();
        if ($redis->has('thisYearHolidays')) {
            return $redis->get('thisYearHolidays');
        }
        $year = date('Y');
        //假期列表
        $holidayUrl = 'https://api.apihubs.cn/holiday/get?field=holiday,date,weekend,workday,holiday_overtime,holiday_legal,holiday_recess' .
            '&year=' . $year .
            '&holiday_recess=1' .
            '&cn=1';
        //调休列表
        $restUrl = 'https://api.apihubs.cn/holiday/get?field=date,weekend,workday,holiday_overtime,holiday_legal,holiday_recess' .
            '&year=' . $year .
            '&holiday_overtime=99' .
            '&cn=1';
        $res = curl($holidayUrl);
        $res1 = curl($restUrl);
        if (isset($res['code']) && $res['code'] == 0) {
            $list = [];
            foreach ($res['data']['list'] as $v) {
                $time = date('Y-m-d', strtotime($v['date']));
                $list['text'][$v['holiday_cn']][] = $time;
                $list['list'][$time] = 2;
            }
            foreach ($res1['data']['list'] as $v) {
                $time = date('Y-m-d', strtotime($v['date']));
                $list['list'][$time] = 1;  //调休 工作日
            }
            $redis->set('thisYearHolidays', $list, 86400);
            return $list;
        }
        return false;
    }
}

if (!function_exists('getVacation')) {
    /**
     * 获取年份假期
     *
     * User : Du
     * Date : 2022/1/8
     * Time : 10:04
     * @param string $year
     * @return array|false
     */
    function getVacation(string $year = '')
    {
        $year = $year ?: date('Y');
        $url = 'https://api.apihubs.cn/holiday/get?field=date,holiday&year=' . $year . '&holiday_recess=1&cn=1';
        $res = curl($url);
        if ($res['code'] !== 0) {
            return false;
        }
        $list = array_reverse($res['data']['list']);
        $data = [];
        foreach ($list as $v) {
            $v['date'] = date('Y-m-d', strtotime($v['date']));
            $data[$v['holiday_cn']][] = $v;
        }
        return $data;
    }
}

if (!function_exists('mobileMosaic')) {
    /**
     * 手机号打*码
     *
     * User : Du
     * Date : 2022/1/8
     * Time : 10:03
     * @param string $mobile
     * @return string|string[]
     */
    function mobileMosaic(string $mobile)
    {
        if ($mobile === '' || strlen($mobile) !== 11) {
            return '';
        }
        return substr_replace($mobile, '****', 3, 4);
    }
}

if (!function_exists('isOneDimensionArray')) {
    /**
     * 判断数组是否是一维数组
     *
     * User : Du
     * Date : 2022/3/8
     * Time : 16:21
     * @param array $arr
     * @return bool true：一维数组 false：多维数组
     */
    function isOneDimensionArray(array $arr = []): bool
    {
        if (count($arr) === count($arr, COUNT_RECURSIVE)) {
            return true;
        }
        return false;
    }
}

if (!function_exists('getAuditNumber')) {
    /**
     * 获取审核编号
     *
     * User : Du
     * Date : 2022/3/30
     * Time : 17:32
     * @param int $number
     * @return string
     */
    function getAuditNumber(int $number): string
    {
        $time = date('Ymd');
        if ($number < 9999) {
            for ($i = strlen($number); $i < 4; $i++) {
                $number = '0' . $number;
            }

        }
        return $time . $number;
    }
}


if (!function_exists('minuteToTime')) {
    /**
     * 时分转换为秒
     *
     * User : Du
     * Date : 2022/7/29
     * Time : 11:58
     * @param int $number
     * @return string
     */
    function minuteToTime(int $number): string
    {
        $hour = intval($number / 60);
        $minute = $number % 60;
        $hour = $hour >= 10 ? $hour : '0' . $hour;
        $minute = $minute >= 10 ? $minute : '0' . $minute;
        return $hour . ':' . $minute;
    }
}

if (!function_exists('arrayToJson')) {
    /**
     * 数组转json
     *
     * User : Du
     * Date : 2022/5/10
     * Time : 9:38
     * @param array $arr
     * @return false|string
     */
    function arrayToJson(array $arr)
    {
        if (!$arr) {
            return '';
        }
        try {
            return json_encode($arr, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
        } catch (JsonException $e) {
            return false;
        }
    }
}

if (!function_exists('jsonToArray')) {
    /**
     * json转数组
     *
     * @param $json
     * @return array|mixed
     */
    function jsonToArray($json)
    {
        if (!$json) {
            return [];
        }
        try {
            return json_decode($json, true, 512, JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            return false;
        }
    }
}

if (!function_exists('getOrderNo')) {
    /**
     * 获取唯一订单号
     * User : Du
     * Date : 2022/11/30
     * Time : 15:48
     * @return string
     */
    function getOrderNo(): string
    {

        $time = date('YmdHis');
        $microsecond = substr(explode('.', microtime(true))[1], 0, 3);
        $random = random_int(0, 9999);
        switch (true) {
            case $random <= 9:
                $random = '000' . $random;
                break;
            case $random <= 99:
                $random = '00' . $random;
                break;
            case $random <= 999:
                $random = '0' . $random;
                break;
        }
        $str = getCode(6, 2);
        return $time . $microsecond . $random . $str;
    }
}

if (!function_exists('updateOnline')) {
    /**
     * workerman更新在线人数
     * @throws Exception
     */
    function updateOnline()
    {
        $res = [
            'type' => 'update_online_count',
            'user_number' => Workerman::getUidCountByGroup(),
            'page_number' => Workerman::getClientIdCountByGroup(),
        ];
        Workerman::sendMessage($res, 'all');
    }
}
if (!function_exists('imagePath')) {
    /**
     * 图片路径处理
     * @param string $path
     * @return array
     */
    function imagePath(string $path): array
    {
        if (!$path || $path === '') {
            return [
                'src' => '',
                'path' => '',
            ];
        }
        if (is_file(public_path() . $path)) {
            return [
                'src' => '/' . $path,
                'path' => $path,
            ];
        }
        return
            [
                'src' => env('qiniu.domain') . $path,
                'path' => $path,
            ];
    }
}

if (!function_exists('getTree')) {
    /**
     * 数组转树形结构
     * @param array $array
     * @param string $key
     * @param string $son
     * @return array
     */
    function getTree(array $array, string $key = 'pid', string $son = 'son'): array
    {
        //遍历数组，按照id作为键名重新组建新的数组
        $data = [];
        foreach ($array as $value) {
            $data[$value['id']] = $value;
        }
        $list = [];
        foreach ($data as $k => $v) {
            if (isset($data[$v[$key]])) {
                $data[$v[$key]][$son][] = &$data[$k];
            } else {
                $list[] = &$data[$k];
            }
        }
        return $list;
//        $return_tree = [];
//        foreach ($new_array as $kk => $vv) {
//            if (isset($new_array[$vv[$key]])) {
//                $new_array[$vv[$key]][$son][] = &$new_array[$kk];
//            } else {
//                $return_tree[] = &$new_array[$kk];
//            }
//        }
//        return $return_tree;
    }
}


if (!function_exists('blogPage')) {
    /**
     * blog页码
     * @param int $total
     * @param int $page
     * @param string $path
     * @return string
     */
    function blogPage(int $total = 1, int $page = 1, string $path = ''): string
    {
        $totalPage = (int)ceil($total / 10);
        $html = '';
        $url = '/' . $path . '/';
        //上一页
        if ($page >= 2) {
            $one = $page - 1;
            $html .= '<a class="extend prev" rel="prev" href="' . $url . $one . '">〈</a>';
            if ($page - 3 >= 1) {
                $html .= '<a class="page-number" href="/page/1">1</a>';
                $html .= '<span class="space">…</span>';
                if ($page === $totalPage) {
                    $two = $page - 2;
                    $html .= '<a class="page-number" href="' . $url . $two . '">' . $two . '</a>';
                }
                $html .= '<a class="page-number" href="' . $url . $one . '">' . $one . '</a>';
            } else {
                if ($page - 2 >= 1) {
                    $two = $page - 2;
                    $html .= '<a class="page-number" href="' . $url . $two . '">' . $two . '</a>';
                }
                if ($page - 1 >= 1) {
                    $html .= '<a class="page-number" href="' . $url . $one . '">' . $one . '</a>';
                }
            }
            $html .= '<span class="page-number current">' . $page . '</span>';
        } else {
            $html .= '<span class="page-number current">1</span>';
        }
        //下一页
        $one = $page + 1;
        if ($totalPage >= $page + 1) {
            $html .= '<a class="page-number" href="' . $url . $one . '">' . $one . '</a>';
        }
        if ($totalPage >= $page + 3) {
            if ($page === 1) {
                $two = $page + 2;
                $html .= '<a class="page-number" href="' . $url . $two . '">' . $two . '</a>';
            }
            $html .= '<span class="space">…</span>';
            $html .= '<a class="page-number" rel="next" href="' . $url . $totalPage . '">' . $totalPage . '</a>';
            $html .= '<a class="extend next" rel="next" href="' . $url . $one . '">〉</a>';
        } else {
            if ($totalPage >= $page + 2) {
                $two = $page + 2;
                $html .= '<a class="page-number" href="' . $url . $two . '">' . $two . '</a>';
            }
            if ($page !== $totalPage) {
                $html .= '<a class="extend next" rel="next" href="' . $url . $one . '">〉</a>';
            }
        }
        return $html;
    }
}

if (!function_exists('getSize')) {
    /**
     * @param int $filesize
     * @return string
     */
    function getSize(int $filesize): string
    {
        if ($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
        } elseif ($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
        } elseif ($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
        }
        return $filesize;
    }
}






//function encrypt(string $str)
//{
//    $key = '123';
//    $data = openssl_encrypt($str, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
//}





